package com.example.springmvcdemo3;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

/**
 * @author Q
 * @create 2025-05-25-9:37
 */
@RequestMapping("/request")
@RestController
public class RequestController {
    //传统写法
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        System.out.println("获取Cookie信息：");
        if(cookies != null) {
            for(Cookie cookie:cookies) {
                System.out.println(cookie.getName()+ ":" + cookie.getValue());
            }
        }
        return "获取Cookie成功";
    }
    //获取单个（不常用）
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("name") String name) {
        System.out.println("从Cookie中获取name: " + name);
        return "从Cookie中获取name: " + name;
    }
    //创建Session
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        //如果为true,证明session对象不存在，则创建一个Session对象
        HttpSession session = request.getSession(true);
        session.setAttribute("name","张三");
        session.setAttribute("studentId","100256");
        return "创建Session成功";
    }
    //获取Session->要先创建Session,否则无法获取到数据
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        //为false,证明存在，不需要创建Session对象
        HttpSession session = request.getSession(false);
        if(session != null) {
            System.out.println(session.getAttribute("name"));
            System.out.println(session.getAttribute("studentId"));
        }
        return "获取Session成功";
    }
    //简约写法2
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        //为false,证明存在，不需要创建Session对象
            System.out.println(session.getAttribute("name"));
            System.out.println(session.getAttribute("studentId"));
        return "获取Session成功";
    }
    //注解获取3
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute(value = "name",required = false) String name) {
        System.out.println("name: " + name);
        return "获取Session成功";
    }
    //获取Header
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        System.out.println("User-Agent: " + userAgent);
        return "User-Agent: " + userAgent;
    }
    //注释获取Header
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        System.out.println("User-Agent: " + userAgent);
        return "User-Agent: " + userAgent;
    }
}
